package com.example.excel.ui.fragment.gallery;

import android.app.Application;

import com.example.excel.base.BaseViewModel;
import com.example.excel.bean.InventoryBean;
import com.example.excel.db.InventoryController;
import com.example.excel.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class GalleryViewModel extends BaseViewModel {
    public MutableLiveData<List<InventoryBean>> mBeans = new MutableLiveData<>();
    public MutableLiveData<Boolean> mStopRefresh = new MutableLiveData<>();
    public int mPageNum;
    public int mTotal = -1;

    public GalleryViewModel(@NonNull Application application) {
        super(application);

    }

    public void listByDB(final int index, int pageNum) {
        mPageNum = pageNum;
        getTxtDialog().setValue("正在加载数据，请稍后...");
        Observable.just(1).map(new Function<Integer, List<InventoryBean>>() {
            @io.reactivex.annotations.NonNull
            @Override
            public List<InventoryBean> apply(@io.reactivex.annotations.NonNull Integer integer) throws Exception {
                if (mTotal == -1) {
                    List<InventoryBean> inventoryBeans = InventoryController.getInstance().queryAll(index);
                    if (inventoryBeans != null) {
                        mTotal = inventoryBeans.size();
                    }
                }
                if (mTotal == -1) {
                    return new ArrayList<>();
                }
                return InventoryController.getInstance().queryInventory(index, mPageNum);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<InventoryBean>>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull List<InventoryBean> inventoryBeans) {
                mBeans.setValue(inventoryBeans);
                getDialog().setValue(false);
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                Utils.getInstance().showToast("e:" + e.getMessage());
                getDialog().setValue(false);
            }

            @Override
            public void onComplete() {
                mStopRefresh.setValue(true);
            }
        });
    }
}